<template>
  <el-dialog width="1200px" destroy-on-close append-to-body :visible.sync="show" :before-close="cancel">
    <template #title>
      <div>
        代做模板 <span style="margin-left: 50px">sku:{{ formData.skuNo }}</span>
      </div>
    </template>

    <div>
      <el-row>
        <div style="display: flex; align-items: center; margin-bottom: 15px">
          <div style="flex: 1">
            sku:{{ info.skuNo }}
            <i style="margin: 0 5px" class="el-icon-document-copy" @click="useCopy(info.skuNo)"></i>
          </div>
          <div style="flex: 1">
            库位号:{{ info.spNo }}
            <i style="margin: 0 5px" class="el-icon-document-copy" @click="useCopy(info.spNo)"></i>
          </div>
        </div>
      </el-row>
      <el-row>
        <div>
          <el-select
            @change="setTemplateInfo"
            style="margin-right: 15px"
            size="mini"
            v-model="selectedTemplate"
            :placeholder="$t('请选择')"
          >
            <el-option v-for="item in templateList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button
            size="mini"
            v-hasPermi="['distribution:skuTempProxy:add']"
            type="primary"
            @click="handleAddTemplate"
            v-show="!disabled">
            新增模板
          </el-button>
        </div>
      </el-row>
      <el-form
        v-if="type"
        ref="formRef"
        :model="form"
        :disabled="disabled"
        :rules="rules"
        label-width="90px"
        style="margin-top: 10px"
      >
        <el-row :gutter="2">
          <el-col :span="6">
            <el-form-item label="sku:" label-width="60px" prop="skuNameJp">
              {{ info.skuNo }}
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="模板名称:" prop="name">
              <el-input v-model="form.name" size="mini"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="平台sku:" prop="skuNo">
              <el-input v-model="form.skuNo" size="mini"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="价格(JPY):" prop="price">
              <el-input
                size="mini"
                v-model="form.price"
                oninput="value=value.replace(/[^\d.]/g, '')"
                controls-position="right"
                :min="0"></el-input>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="标题:" prop="title">
              <el-input v-model="form.title" size="mini"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 15px">
          <el-col :span="10">
            <!-- 五点描述 -->
            <div class="des-title">五点描述</div>
            <el-descriptions :column="1" border class="des-desc5">
              <el-descriptions-item label="描述1" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc1">
                  <el-input v-model="form.desc1" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="描述2" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc2">
                  <el-input v-model="form.desc2" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="描述3" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc3">
                  <el-input v-model="form.desc3" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="描述4" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc4">
                  <el-input v-model="form.desc4" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="描述5" label-class-name="my-label5" content-class-name="my-content">
                <el-form-item label-width="0" prop="desc5">
                  <el-input v-model="form.desc5" />
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="10">
            <!-- 详细描述 -->
            <div class="des-title">详细描述</div>
            <div class="des-detail">
              <div class="des-detail_left">详情</div>
              <div class="des-detail_right">
                <el-form-item label-width="0" prop="descDetails">
                  <el-input
                    style="height: 100%"
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="form.descDetails"
                    :rows="10"
                  />
                </el-form-item>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div>
              <!-- 已完成的模板也允许修改 -->
              <el-button
                type="primary"
                size="small"
                style="margin: 5px 0"
                @click="handleEdit"
                v-hasPermi="['distribution:skuTempProxy:edit']"
                v-show="!disabled && type != 'add' && selectedTemplate">
                修改模板
              </el-button>
              <div v-show="type == 'edit'">
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteTemplate"
                  v-hasPermi="['distribution:skuTempProxy:remove']"
                  v-show="selectedTemplate && form.isComplete != 1">
                  删除模板
                </el-button>
              </div>
              <div v-show="type == 'add'">
                <el-button
                  v-hasPermi="['distribution:skuTempProxy:add']"
                  type="success"
                  size="small"
                  @click="addTemplate"
                >
                  确认新增
                </el-button>
              </div>
              <div>
                <div>创建人:{{ form.createByName }}</div>
                <div>创建时间:{{ form.createTime }}</div>
                <div>更新人:{{ form.updateByName }}</div>
                <div>更新时间:{{ form.updateTime }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
        <div v-if="type == 'edit' || type == ''">
          <div style="padding: 10px 0">模板图片</div>
          <el-row>
            <div class="template-img" :style="disabled ? 'pointer-events: none;' : ''">
              <div class="template-img-list">
                <ImgUploadManage
                  type="10"
                  :businessId="form.id"
                  :uploadLimit="10"
                  :limit="10"
                  :fileList.sync="tempProxyImgList"
                />
              </div>
              <div class="template-img-btns">
                <el-button size="small" @click="handleSaveImg" v-hasPermi="['distribution:skuTempProxy:updateImg']">
                  保存图片
                </el-button>
                <div>
                  <div>创建人:{{ imgInfo.createByName }}</div>
                  <div>创建时间:{{ imgInfo.createTime }}</div>
                  <div>更新人:{{ imgInfo.updateByName }}</div>
                  <div>更新时间:{{ imgInfo.updateTime }}</div>
                </div>
              </div>
            </div>
          </el-row>
        </div>
      </el-form>
      <div style="text-align: right; margin-top: 30px">
        <el-button disabled v-if="form.isComplete == 1"> 已完成 </el-button>

        <!-- isComplete==1 已完成模板 -->
        <el-button
          v-show="form.isComplete != 1 && type !== 'add' && selectedTemplate"
          v-hasPermi="['distribution:skuTempProxy:completeTemp']"
          @click="handleCompleteTemp"
        >
          完成模板
        </el-button>

        <el-button @click="cancel">关 闭</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  acceptanceTemp,
  add,
  completeTemp,
  edit,
  getSkuProxyTemplateList,
  skuTempProxyDelete,
  updateImg,
} from '@/api/distribution/sku/skuTempProxyApply'
import draggable from 'vuedraggable'
export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  components: { draggable },
  props: {
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
    skuId: {
      type: String,
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
  },
  data() {
    return {
      tempProxyImgList: '',
      drag: false,
      imgInfo: {
        createByName: '',
        createTime: '',
        updateByName: '',
        updateTime: '',
      },
      //定义要被拖拽对象的数组
      myArray: [
        { people: 'cn', id: 1, name: 'www.itxst.com' },
        { people: 'cn', id: 2, name: 'www.baidu.com' },
        { people: 'cn', id: 3, name: 'www.taobao.com' },
      ],
      isShowDialog: false,
      waitUploadList: [],
      uploadFlag: false,
      info: { skuNo: '', spNo: '' },
      backFormDate: {},
      selectedTemplate: '',
      /**模式 */
      type: '',
      form: {
        id: '',
        skuId: '',
        skuNo: '',
        /**模板名称 */
        name: '',
        /**价格(JPY) */
        price: '',
        /**标题 */
        title: '',
        /**描述1 */
        desc1: '',
        /**描述2 */
        desc2: '',
        /**描述3 */
        desc3: '',
        /**描述4 */
        desc4: '',
        /**描述5 */
        desc5: '',
        /**详情 */
        descDetails: '',
        /**完成状态 */
        isComplete: '',
        distrId: '',
        /**模板图片 */
        tempProxyImgList: [],
        createByName: '',
        createTime: '',
        updateByName: '',
        updateTime: '',
      },
      rules: {
        name: [{ validator: this.validLength, required: true, trigger: 'change' }],
        // skuNo: [{ required: true, message: '请输入', trigger: 'blur' }],
        // price: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ validator: this.validLength, required: true, trigger: 'change' }],
        combinationSku: [{ required: true, message: '请输入', trigger: 'blur' }],
        title: [{ validator: this.validLength, required: true, trigger: 'change' }],
        desc1: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc2: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc3: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc4: [{ validator: this.validLength, required: false, trigger: 'change' }],
        desc5: [{ validator: this.validLength, required: false, trigger: 'change' }],
        descDetails: [{ validator: this.validLength, required: false, trigger: 'change' }],
      },
      templateList: [],
      // 查询参数
      queryParams: {},
    }
  },
  computed: {},
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.getList()
      }
    },
  },
  methods: {
    //开始拖拽事件
    onStart() {
      this.drag = true
    },
    //拖拽结束事件
    onEnd() {
      this.drag = false
    },
    handleSaveImg() {
      const data = {
        tempId: this.selectedTemplate,
        imgUrlList: this.tempProxyImgList?.split(',')?.map((i, index) => {
          return {
            imgUrl: i,
            sort: index + 1,
          }
        }),
      }
      updateImg(data).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.$message({ type: 'success', message: msg })
          this.getList()
        }
      })
    },
    handleCompleteTemp() {
      this.$confirm('确定完成模板?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        completeTemp(this.selectedTemplate).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })
            this.cancel()
            this.$emit('getList')
          }
        })
      })
    },
    handleAcceptanceTemp() {
      const message = this.$t('请确定全部完成后验收，验收完成时会将文案代做的模板追加到该sku的模板上')
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        acceptanceTemp(this.formData.id).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })
            this.cancel()
            this.$emit('getList')
          }
        })
      })
    },
    /**验证长度 */
    validLength(rule, value, callback) {
      const { field } = rule
      const strLength = value.length

      // name
      if (field == 'name') {
        if (!value) {
          return callback(new Error(`请输入`))
        }
        //  长度最大为 20
        if (strLength > 20) {
          return callback(new Error(`文字超长 ${strLength} / 20`))
        }
      }
      // descDetails
      if (field == 'descDetails') {
        //  长度最大为 3000
        if (strLength > 3000) {
          return callback(new Error(`文字超长 ${strLength} / 3000`))
        }
      }

      // title
      if (field == 'title') {
        if (!value) {
          return callback(new Error(`请输入`))
        }
        //  长度最大为 300
        if (strLength > 300) {
          return callback(new Error(`文字超长 ${strLength} / 300`))
        }
      }

      // 五点描述 长度最大为 500
      if (field == 'desc1' || field == 'desc2' || field == 'desc3' || field == 'desc4' || field == 'desc5') {
        // 五点描述 长度最大为 500
        if (strLength > 500) {
          return callback(new Error(`文字超长 ${strLength} / 500`))
        }
      }
      return callback()
    },
    handleRemoveFile(index) {
      this.form.tempProxyImgList.splice(index, 1)
      this.$refs['uploadRef'].uploadFiles?.splice(index, 1)
    },
    resetForm() {
      Object.keys(this.form).forEach((key) => (this.form[key] = ''))
      this.form.tempProxyImgList = []
      this.form.skuId = this.skuId
    },
    // 验证数据是否改变
    validFormData() {
      let flag = null
      if (JSON.stringify(this.backFormDate) == JSON.stringify(this.form)) {
        flag = false
      } else {
        flag = true
      }

      return flag
    },
    onChange(file, fileList) {
      if (this.uploadFlag) {
        return this.waitUploadList.push(file.raw)
      }
      this.uploadFlag = true
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      const formData = new FormData()
      formData.append('file', file.raw)
      this.$upload('/system/oss/upload', formData)
        .then((res) => {
          const { code, data } = res
          if (code == 200) {
            this.form.tempProxyImgList.push({
              templateImgUrl: data.url,
              skuTemplateId: this.selectedTemplate,
            })
            this.uploadFlag = false
            this.uploadRestFile()
          }
        })
        .finally(() => loading.close())
    },
    /**上传翻个文件 */
    uploadSingleFile() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      const formData = new FormData()
      const file = this.waitUploadList.shift()
      formData.append('file', file)
      this.$upload('/system/oss/upload', formData)
        .then((res) => {
          const { code, data } = res
          if (code == 200) {
            this.form.tempProxyImgList.push({
              templateImgUrl: data.url,
              skuTemplateId: this.selectedTemplate,
            })
            this.uploadRestFile()
          }
        })
        .finally(() => loading.close())
    },

    /**上传剩余文件 */
    uploadRestFile() {
      if (this.waitUploadList.length > 0) {
        this.uploadSingleFile()
      }
    },
    handleAddTemplate() {
      if (this.formData.num <= this.templateList.length) {
        this.$message({ type: 'error', message: '模板数量不能超过申请数量' })
        return
      }
      this.resetForm()
      this.type = 'add'
      this.selectedTemplate = ''
    },
    deleteTemplate() {
      this.$confirm(this.$t('确认删除?'), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        skuTempProxyDelete(this.selectedTemplate).then((res) => {
          if (res.code == 200) {
            this.$message({ type: 'success', message: res.msg })
            this.getList()
          }
        })
      })
    },

    setTemplateInfo(id, flag = false) {
      this.resetForm()
      const info = this.templateList.filter((item) => item.id == id || item.name == id)[0] || {}
      this.selectedTemplate = info.id

      Object.keys(this.form).forEach((key) => {
        const _data = JSON.parse(JSON.stringify(info))
        if (key == 'tempProxyImgList') {
          this.tempProxyImgList = (_data[key] || [])?.map((i) => i.templateImgUrl)?.toString()
          this.form[key] = _data[key] ? _data[key] : []
        } else {
          this.form[key] = _data[key]
        }
      })
      if (flag) {
        this.backFormDate = JSON.parse(JSON.stringify(this.form))
      }
      this.type = 'edit'
    },
    addTemplate() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify({ ...this.form, applyId: this.formData.id }))
          add(data).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              const templateName = JSON.parse(JSON.stringify(this.form.name))
              this.getList(true, templateName)
              this.type = ''
            }
          })
        }
      })
    },
    handleEdit() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = {
            ...this.form,
            applyId: this.formData.id,
          }
          edit(data).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              const templateName = JSON.parse(JSON.stringify(this.form.name))
              this.getList(true, templateName)
              this.type = ''
            }
          })
        }
      })
    },
    setImgInfo(data) {
      if (data) {
        this.imgInfo = {
          createByName: data.createByName,
          createTime: data.createTime,
          updateByName: data.updateByName,
          updateTime: data.updateTime,
        }
      }
    },
    getList(flag = false, templateName = null) {
      getSkuProxyTemplateList({ id: this.formData.id }).then((res) => {
        const { tempProxyList, skuNo, spNo } = res.data
        this.setImgInfo(tempProxyList[0])

        /***************************头部信息******************************/
        this.info.skuNo = skuNo
        this.info.spNo = spNo
        /***************************头部信息******************************/
        this.templateList = tempProxyList || []

        /***************************设置相关信息******************************/
        if (templateName) {
          this.setTemplateInfo(templateName, flag)
        } else {
          this.setTemplateInfo(this.templateList[0]?.id, flag)
        }
        /***************************设置相关信息******************************/

        if (this.templateList.length == 0) {
          this.type = ''
        }
      })
    },
    submitForm() {},
    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style lang="scss" scoped>
/*被拖拽对象的样式*/
.item {
  padding: 6px;
  background-color: #fdfdfd;
  border: solid 1px #eee;
  margin-bottom: 10px;
  cursor: move;
}
/*选中样式*/
.chosen {
  border: solid 2px #3089dc !important;
}
.des-desc5 {
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}
.el-form-item {
  // margin-bottom: 5px;
}

.my-label5 {
  text-align: center !important;
}

.des-title {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  border: 1px solid #e1dddd;
  border-bottom: none;
}

.des-detail {
  display: flex;
  height: 265px;
  border: 1px solid #e1dddd;

  &_left {
    width: 40%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #e1dddd;
  }

  &_right {
    padding: 10px;
    flex: 1;

    ::v-deep textarea {
      height: 100%;
    }
  }
}

.template-img {
  display: flex;
  overflow: auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 5px;
  &-list {
    width: calc(100% - 200px);
    display: flex;
    overflow: auto;
  }
  &-btns {
    width: 200px;
    padding: 5px;
    display: flex;
    flex-direction: column;
  }
}
</style>
